import { onHide } from '@dcloudio/uni-app';
<!--
 * @Description:
 * @Date: 2024-05-14 09:00:16
 * @LastEditTime: 2024-08-26 14:57:19
-->
<route lang="json5" type="mine">
{
  style: {
    navigationBarTitleText: '检察官视频接访',
    navigationBarTextStyle: 'white', //标题栏字体颜色
    navigationBarBackgroundColor: '#0063AF', //标题栏背景色(纯色)
  },
}
</route>
<template>
  <wd-notice-bar
    type="danger"
    text="请及时点击确认审核通过，在申请时间段联系市民进行视频！"
    :scrollable="false"
  />
  <view class="w-screen h-screen flex flex-col p-20rpx box-border pt-0 bg-#ffffff">
    <div class="date">
      <span class="mr-2">时间段</span>
      <wd-radio-group v-model="dateRange" shape="button" @change="handleDateChange">
        <wd-radio :value="7">近一周</wd-radio>
        <wd-radio :value="30">近一个月</wd-radio>
        <wd-radio :value="3">全部</wd-radio>
      </wd-radio-group>
    </div>
    <wd-tabs v-model="tabVal" @change="handleTabChange">
      <wd-tab v-for="tabItem in tabList" :key="tabItem" :title="tabItem" :name="tabItem"></wd-tab>
    </wd-tabs>
    <div class="interview">
      <div class="interview-item" v-for="interview in interviewList" :key="interview.id">
        <span @click="toDetails(interview)">
          <div class="interview-item__title">
            <span>{{ customDate(interview) }}</span>
            <span v-if="tabVal === '审核通过'" class="ml-4" style="color: #db3934">
              {{ awayTodayDate(interview) }}
            </span>
          </div>
          <div class="interview-item__content">
            <div class="flex">
              <span class="mr-4">预约人姓名</span>
              <span>{{ interview.name }}</span>
            </div>
            <div class="flex mt-1">
              <span class="mr-4">预约时段</span>
              <span>{{ interview.requestTime }}</span>
            </div>
          </div>
        </span>
        <div class="interview-item__btns">
          <div v-if="tabVal === '待审核'" class="flex">
            <div class="refuse-btn" @click.stop="handleRefuse(interview)">驳回</div>
            <div class="pass-btn" @click.stop="handlePass(interview)">通过</div>
            <!-- <wd-button class="mr-2" size="small" plain>驳回</wd-button> -->
            <!-- <wd-button size="small" @click.stop="handlePass(interview)">通过</wd-button> -->
          </div>
          <span v-else-if="tabVal === '审核通过'">
            <span style="color: #db3934" class="mr-2">
              {{ `房间号：${interview.meetingNumber}` }}
            </span>
            <wd-button size="small" @click.stop="toInterviewMeeting">立即前往视频</wd-button>
          </span>
        </div>
        <div v-if="tabVal === '审核驳回'" class="mt-4">
          <span style="color: #db3934">{{ `驳回原因：${interview.auditingContent}` }}</span>
        </div>
      </div>
    </div>
    <wd-status-tip
      v-if="interviewList.length == 0"
      :image-size="{
        height: 200,
        width: 300,
      }"
      image="search"
      tip="当前搜索无结果"
    />
    <wd-loadmore v-if="interviewList.length > 0" :state="loadState" @reload="loadmore" />
  </view>
</template>

<script setup lang="ts">
import { useUserStore } from '@/store'
import { useToast, useMessage } from 'wot-design-uni'
import { getJianChaListAPI, updateStatusAPI } from '@/service/index/foo'

const message = useMessage()
const toast = useToast()
const baseurl = import.meta.env.VITE_SERVER_BASEURL
const userStore = useUserStore()

const dateRange = ref(7)
const tabVal = ref('待审核')
const tabList = ['待审核', '审核通过', '审核驳回']
const max = ref(60)
const loadState = ref('loading')
const interviewList = ref([])
const filterDateList = ref([])
const pages = reactive({
  pageNo: 1,
  pageSize: 10,
})

onShow(() => {
  handleDateChange(7)
})

onReachBottom(() => {
  if (interviewList.value.length === max.value) {
    loadState.value = 'finished'
  } else if (interviewList.value.length < max.value) {
    pages.pageNo += 1
    loadmore()
  }
})

onPullDownRefresh(async () => {
  pages.pageNo = 1
  interviewList.value.length = 0
  getInterviewList()
  uni.stopPullDownRefresh()
})

function loadmore() {
  loadState.value = 'loading'
  setTimeout(() => {
    getInterviewList()
  }, 1000)
}

// 日期过滤选择
async function handleDateChange(val) {
  interviewList.value.length = 0
  const range = val.value || val
  filterDateList.value = []
  if (val.value !== 3) {
    const today = new Date()
    for (let i = 0; i <= range; i++) {
      const date = new Date(today)
      date.setDate(today.getDate() + i)
      const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
      filterDateList.value.push(formattedDate)
    }
  }
  await getInterviewList()
}

// tab切换
function handleTabChange(val) {
  tabVal.value = val.name || val
  loadState.value = 'loading'
  interviewList.value.length = 0
  pages.pageNo = 1
  getInterviewList()
}

// 获取列表数据
function getInterviewList() {
  const timeList = filterDateList.value.length
    ? [filterDateList.value[0], filterDateList.value[filterDateList.value.length - 1]]
    : []

  const statusObj = {
    待审核: 1,
    审核通过: 2,
    审核驳回: 3,
  }
  const params = {
    pageNo: pages.pageNo,
    pageSize: pages.pageSize,
    status: statusObj[tabVal.value],
    acceptUserId: userStore.userInfo.userId,
    acceptTime: timeList.length ? timeList.join(',') : null,
  }
  getJianChaListAPI(params).then((res) => {
    interviewList.value.push(...res.data.list)
    max.value = res.data.total
    interviewList.value.length === max.value
      ? (loadState.value = 'finished')
      : (loadState.value = 'loading')
  })
}

// 详情
function toDetails(interview) {
  uni.navigateTo({
    url: `/pages/mine/serviceDetails?id=${interview.id}`,
  })
}

// 审核通过
function handlePass(interview) {
  const data = {
    id: interview.id,
    status: 2,
  }
  updateStatusAPI(data).then((res) => {
    if (res.data) {
      toast.success('审核通过提交成功')
      handleTabChange(tabVal.value)
    } else {
      toast.error('审核提交失败')
    }
  })
}

// 审核驳回
function handleRefuse(interview) {
  message
    .prompt({
      title: '请输入驳回理由',
      inputPattern: /^.+$/,
      inputError: '驳回理由不能为空',
    })
    .then((resp) => {
      const data = {
        id: interview.id,
        status: 3,
        auditingContent: resp.value,
      }
      updateStatusAPI(data).then(() => {
        toast.success('审核驳回提交成功')
      })
      handleTabChange(tabVal.value)
    })
    .catch((error) => {
      console.log(error)
    })
}

// 前往接访视频
function toInterviewMeeting() {
  uni.navigateTo({ url: '/pages/menu/videoCall/index' })
}

function customDate(interview) {
  const daysOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  const date = new Date(interview.acceptTime)
  const dayIndex = date.getDay()
  const week = daysOfWeek[dayIndex]

  return `${interview.acceptTime}  ${week}`
}

function awayTodayDate(interview) {
  const today = new Date()
  const targetDate = new Date(interview.acceptTime)
  const timeDiff = targetDate.getTime() - today.getTime()
  const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24))
  return daysDiff === 0 ? '今天' : `${daysDiff}天后`
}
</script>
<style lang="scss" scoped>
.date {
  display: flex;
  align-items: center;
  padding: 0px 8px;
  margin-top: 8px;
}

.interview {
  padding: 4px 8px;

  &-item {
    display: flex;
    flex-direction: column;
    padding: 8px 16px;
    margin-bottom: 16px;
    border-radius: 10px;
    box-shadow: 0px 0px 5px 5px #f0f0f0 !important;

    &__title {
      margin-bottom: 16px;
      font-size: 16px;
      font-weight: bold;
    }

    &__content {
      display: flex;
      flex-direction: column;
      margin-bottom: 4px;
      font-size: 14px;
    }

    &__btns {
      margin-left: auto;
    }
  }
}

.refuse-btn {
  display: flex;
  align-items: center;
  padding: 2px 24px;
  margin-right: 16px;
  font-size: 12px;
  color: #4c7ff0;
  border: 1px solid #4c7ff0;
  border-radius: 30px;
}

.pass-btn {
  display: flex;
  align-items: center;
  padding: 2px 24px;
  font-size: 12px;
  color: #fff;
  background: #4d80f0;
  border-radius: 30px;
}

::v-deep .wd-radio__label {
  color: #006dff;
  background: #fff !important;
  border: 2rpx solid #649dff !important;
  border-radius: 10rpx !important;
}

::v-deep .is-checked > .wd-radio__label {
  color: #fff !important;
  background: #006eff !important;
  border: none !important;
}
</style>
